package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FormLabelGroupEnum;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasUserModel;
import com.xbongbong.paas.service.FormLabelService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.domain.entity.FormLabelEntity;
import com.xbongbong.pro.domain.entity.FormTeamSetEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemLabelErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formlabel.dto.FormLabelAddDTO;
import com.xbongbong.pro.formlabel.dto.FormLabelBaseDTO;
import com.xbongbong.pro.formlabel.dto.FormLabelDeleteDTO;
import com.xbongbong.pro.formlabel.dto.FormLabelListDTO;
import com.xbongbong.pro.formlabel.dto.FormLabelUpdateDTO;
import com.xbongbong.pro.formlabel.vo.FormLabelAddVO;
import com.xbongbong.pro.formlabel.vo.FormLabelBaseVO;
import com.xbongbong.pro.formlabel.vo.FormLabelDeleteVO;
import com.xbongbong.pro.formlabel.vo.FormLabelListVO;
import com.xbongbong.pro.formlabel.vo.FormLabelUpdateVO;
import com.xbongbong.pro.label.pojo.LabelGroupListPojo;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.label.pojo.LabelSortPojo;
import com.xbongbong.pro.label.pojo.dto.LabelSortDTO;
import com.xbongbong.pro.label.pojo.vo.LabelGroupListVO;
import com.xbongbong.pro.label.pojo.vo.LabelSortVO;
import com.xbongbong.pro.model.FormLabelModel;
import com.xbongbong.pro.model.FormTeamSetModel;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.model.BomUserModel;
import com.xbongbong.saas.model.ClueUserModel;
import com.xbongbong.saas.model.ContactUserModel;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.MarketActivityUserModel;
import com.xbongbong.saas.model.OpportunityUserModel;
import com.xbongbong.saas.model.PayPlanSheetUserModel;
import com.xbongbong.saas.model.PayPlanUserModel;
import com.xbongbong.saas.model.PaymentSheetUserModel;
import com.xbongbong.saas.model.PaymentUserModel;
import com.xbongbong.saas.model.ProductionOrderUserModel;
import com.xbongbong.saas.model.PurchaseUserModel;
import com.xbongbong.saas.model.QuotationUserModel;
import com.xbongbong.saas.model.RefundUserModel;
import com.xbongbong.saas.model.SupplierContactUserModel;
import com.xbongbong.saas.model.SupplierUserModel;
import com.xbongbong.sys.enums.LabelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 *
 * @author 魏荣杰
 *
 */
@Service("formLabelService")
@Slf4j
public class FormLabelServiceImpl implements FormLabelService {

    @Resource
    private FormLabelModel formLabelModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private ContactUserModel contactUserModel;
    @Resource
    private OpportunityUserModel opportunityUserModel;
    @Resource
    private QuotationUserModel quotationUserModel;
    @Resource
    private ContractUserModel contractUserModel;
    @Resource
    private RefundUserModel refundUserModel;
    @Resource
    private PaymentUserModel paymentUserModel;
    @Resource
    private PaymentSheetUserModel paymentSheetUserModel;
    @Resource
    private PayPlanUserModel payPlanUserModel;
    @Resource
    private PayPlanSheetUserModel payPlanSheetUserModel;
    @Resource
    private SupplierUserModel supplierUserModel;
    @Resource
    private SupplierContactUserModel supplierContactUserModel;
    @Resource
    private PurchaseUserModel purchaseUserModel;
    @Resource
    private BomUserModel bomUserModel;
    @Resource
    private ProductionOrderUserModel productionOrderUserModel;
    @Resource
    private MarketActivityUserModel marketActivityUserModel;
    @Resource
    private ClueUserModel clueUserModel;
    @Resource
    private PaasUserModel paasUserModel;
    @Resource
    private FormTeamSetModel formTeamSetModel;

    @Override
    public FormLabelAddVO add(FormLabelAddDTO formLabelAddDTO) throws XbbException {
        String corpid = formLabelAddDTO.getCorpid();
        Long formId = formLabelAddDTO.getFormId();
        Integer saasMark = formLabelAddDTO.getSaasMark();
        Integer businessType = formLabelAddDTO.getBusinessType();
        Integer distributorMark = formLabelAddDTO.getDistributorMark();
        String name = formLabelAddDTO.getName();
        UserVO loginUser = formLabelAddDTO.getLoginUser();
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put("delIn", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.DELETE.getDel()));
        param.put(ParameterConstant.NAME, name);
        param.put(ParameterConstant.DISTRIBUTOR_ID, distributorMark);
        param.put(ParameterConstant.FORMID, formId);
        param.put(StringConstant.SAAS_MARK, saasMark);
        param.put(ParameterConstant.BUSINESS_TYPE, businessType);

        List<FormLabelEntity> formLabelEntities = formLabelModel.findEntities(param);
        if (CollectionsUtil.isNotEmpty(formLabelEntities)) {
            if (Objects.equals(formLabelEntities.get(0).getDel(), DelEnum.NORMAL.getDel())) {
                throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_392001);
            } else {
                throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_392002);
            }
        }


        param.clear();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.DISTRIBUTOR_ID, distributorMark);
        param.put(ParameterConstant.FORMID, formId);
        param.put(StringConstant.SAAS_MARK, saasMark);
        param.put(ParameterConstant.BUSINESS_TYPE, businessType);

        List<FormLabelEntity> formLabelEntityList = formLabelModel.findEntities(param);
        if (formLabelEntityList.size() >= PaasConstant.LIMIT_MAX_NUM_LABEL) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120012);
        }

        FormLabelEntity formLabelEntity = new FormLabelEntity();
        formLabelEntity.setCorpid(corpid);
        formLabelEntity.setFormId(formId);
        formLabelEntity.setSaasMark(saasMark);
        formLabelEntity.setBusinessType(businessType);
        formLabelEntity.setDistributorMark(distributorMark);
        formLabelEntity.setName(name);
        formLabelEntity.setColor(formLabelAddDTO.getColor());
        formLabelEntity.setCreatorId(formLabelAddDTO.getLoginUser().getUserId());
        long now = DateTimeUtil.getInt();
        formLabelEntity.setAddTime(now);
        formLabelEntity.setUpdateTime(now);
        formLabelEntity.setDel(DelEnum.NORMAL.getDel());
        List<Integer> sortList = formLabelEntityList.stream().map(FormLabelEntity::getSort).collect(Collectors.toList());
        formLabelEntity.setSort(CollectionUtils.isEmpty(sortList) ? Constant.ONE : Collections.max(sortList) + Constant.ONE);

        formLabelModel.insert(formLabelEntity);

        //日志
        PaasFormEntityExt passForm = paasFormModel.getByKey(formId, corpid);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_FORM_LABEL_ADD),loginUser.getName(),passForm.getName(),formLabelAddDTO.getName());
        mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.FORM_LABEL, OperateTypeEnum.NEW,formLabelEntity.getId().toString(),formLabelEntity.getName(),memo,formLabelAddDTO.getHttpHeader());

        FormLabelAddVO formLabelAddVO = new FormLabelAddVO();
        formLabelAddVO.setId(formLabelAddVO.getId());
        return formLabelAddVO;
    }


    @Override
    public FormLabelUpdateVO update(FormLabelUpdateDTO formLabelUpdateDTO) throws XbbException {
        String corpid = formLabelUpdateDTO.getCorpid();
        Long id = formLabelUpdateDTO.getId();
        String name = formLabelUpdateDTO.getName();
        UserVO loginUser = formLabelUpdateDTO.getLoginUser();
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put("delIn", Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.DELETE.getDel()));
        param.put(ParameterConstant.NAME, name);
        param.put("idNot", id);
        List<FormLabelEntity> formLabelEntities = formLabelModel.findEntities(param);
        if (CollectionsUtil.isNotEmpty(formLabelEntities)) {
            if (Objects.equals(formLabelEntities.get(0).getDel(), DelEnum.NORMAL.getDel())) {
                throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_392001);
            } else {
                throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_392002);
            }
        }

        FormLabelEntity formLabelEntity = formLabelModel.getByKey(id, corpid);
        if (Objects.isNull(formLabelEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);

        }

        formLabelEntity.setName(name);
        formLabelEntity.setColor(formLabelUpdateDTO.getColor());
        formLabelEntity.setUpdateTime(DateTimeUtil.getInt());
        formLabelModel.update(formLabelEntity);
        //日志
        PaasFormEntityExt passForm = paasFormModel.getByKey(formLabelEntity.getFormId(), corpid);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_FORM_LABEL_EDIT),loginUser.getName(),passForm.getName(),formLabelUpdateDTO.getName());
        mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.FORM_LABEL, OperateTypeEnum.EDIT,formLabelEntity.getId().toString(),formLabelEntity.getName(),memo,formLabelUpdateDTO.getHttpHeader());

        FormLabelUpdateVO formLabelUpdateVO = new FormLabelUpdateVO();
        formLabelUpdateVO.setId(formLabelEntity.getId());
        return formLabelUpdateVO;

    }

    @Override
    public LabelGroupListVO groupList(BaseDTO baseDTO) throws XbbException {

        List<LabelGroupListPojo> labelTree = new ArrayList<>();

        for (FormLabelGroupEnum value : FormLabelGroupEnum.values()) {
            LabelGroupListPojo labelGroupListPojo = new LabelGroupListPojo();
            labelGroupListPojo.setId(value.getId());
            labelGroupListPojo.setName(value.getName());
            labelGroupListPojo.setSort(value.getSort());
            labelTree.add(labelGroupListPojo);
        }

        LabelGroupListVO labelGroupListVO = new LabelGroupListVO();
        labelGroupListVO.setLabelTree(labelTree);
        return labelGroupListVO;
    }

    @Override
    public FormLabelListVO list(FormLabelListDTO formLabelListDTO) throws XbbException {
        String corpid = formLabelListDTO.getCorpid();
        Long groupId = formLabelListDTO.getGroupId();

        List<LabelPojo> labelListVO = new ArrayList<>();
        if (Objects.equals(groupId, FormLabelGroupEnum.DEFAULT_GROUP.getId())) {
            // 默认分组
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            param.put(ParameterConstant.FORMID, formLabelListDTO.getFormId());
            param.put(StringConstant.SAAS_MARK, formLabelListDTO.getSaasMark());
            param.put(ParameterConstant.BUSINESS_TYPE, formLabelListDTO.getBusinessType());
            param.put(StringConstant.DISTRIBUTOR_MARK, formLabelListDTO.getDistributorMark());
            List<FormLabelEntity> formLabelEntities = formLabelModel.findEntities(param);
            formLabelEntities.forEach(v -> labelListVO.add(new LabelPojo(v.getId(), v.getName(), v.getColor(), v.getSort())));
        } else {
            // 回收站
            Map<String, Object> param = new HashMap<>();
            param.put(ParameterConstant.CORPID, corpid);
            param.put(ParameterConstant.DEL, DelEnum.DELETE.getDel());
            param.put(ParameterConstant.FORMID, formLabelListDTO.getFormId());
            param.put(StringConstant.SAAS_MARK, formLabelListDTO.getSaasMark());
            param.put(ParameterConstant.BUSINESS_TYPE, formLabelListDTO.getBusinessType());
            param.put(StringConstant.DISTRIBUTOR_MARK, formLabelListDTO.getDistributorMark());
            List<FormLabelEntity> formLabelEntities = formLabelModel.findEntities(param);
            formLabelEntities.forEach(v -> labelListVO.add(new LabelPojo(v.getId(), v.getName(), v.getColor(), v.getSort())));
        }

        FormLabelListVO formLabelListVO = new FormLabelListVO();
        formLabelListVO.setLabelListVO(labelListVO);
        return formLabelListVO;
    }


    @Override
    public FormLabelDeleteVO delete(FormLabelDeleteDTO formLabelDeleteDTO) throws XbbException {
        String corpid = formLabelDeleteDTO.getCorpid();
        UserVO loginUser = formLabelDeleteDTO.getLoginUser();
        List<FormLabelEntity> formLabelEntities = formLabelModel.getByLabelIdIn(corpid, formLabelDeleteDTO.getIds());
        if (CollectionUtils.isEmpty(formLabelEntities)) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120019);
        }

        long now = DateTimeUtil.getInt();
        formLabelEntities.forEach(v -> {
            v.setDel(DelEnum.DELETE.getDel());
            v.setUpdateTime(now);
        });
        formLabelModel.updateBatch(formLabelEntities, corpid);

        //日志
        PaasFormEntityExt passForm = paasFormModel.getByKey(formLabelDeleteDTO.getFormId(), corpid);
        String memo;
        ArrayList<String> labels = new ArrayList<>();
        formLabelEntities.forEach(formLabel ->
                labels.add(formLabel.getName())
        );
        String labelNames = StringUtils.join(labels, "，");
        if(formLabelEntities.size() == 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_FORM_LABEL_DEL),loginUser.getName(),passForm.getName(),passForm.getName(),labelNames);
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.FORM_LABEL, OperateTypeEnum.TO_RECYCLE_BIN,formLabelEntities.get(Constant.ZERO).getId().toString(),labelNames,memo,formLabelDeleteDTO.getHttpHeader());
        }else if(formLabelEntities.size() > 1){
            memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_FORM_LABEL_DEL_MATCH),loginUser.getName(),passForm.getName(),labelNames);
            mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.FORM_LABEL, OperateTypeEnum.TO_RECYCLE_BIN,"",labelNames,memo,formLabelDeleteDTO.getHttpHeader());
        }


        FormLabelDeleteVO formLabelDeleteVO = new FormLabelDeleteVO();
        formLabelDeleteVO.setIds(formLabelDeleteDTO.getIds());
        return formLabelDeleteVO;
    }


    @Override
    public FormLabelBaseVO recover(FormLabelBaseDTO formLabelBaseDTO) throws XbbException {
        String corpid = formLabelBaseDTO.getCorpid();
        Long id = formLabelBaseDTO.getId();
        UserVO loginUser = formLabelBaseDTO.getLoginUser();
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.DISTRIBUTOR_ID, formLabelBaseDTO.getDistributorMark());
        param.put(ParameterConstant.FORMID, formLabelBaseDTO.getFormId());
        param.put(StringConstant.SAAS_MARK, formLabelBaseDTO.getSaasMark());
        param.put(ParameterConstant.BUSINESS_TYPE, formLabelBaseDTO.getBusinessType());
//        Integer entityCount = formLabelModel.getEntityCount(param);
        List<FormLabelEntity> formLabelEntityList = formLabelModel.findEntities(param);
        if (formLabelEntityList.size() >= PaasConstant.LIMIT_MAX_NUM_LABEL) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120012);
        }
        FormLabelEntity formLabelEntity = formLabelModel.getByKey(id, corpid);
        if (Objects.isNull(formLabelEntity)) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120019);
        }
        //恢复的标签要展示在最上方，更新sort值
        List<Integer> sortList = formLabelEntityList.stream().map(FormLabelEntity::getSort).collect(Collectors.toList());
        formLabelEntity.setSort(CollectionUtils.isEmpty(sortList) ? Constant.ONE : Collections.max(sortList) + Constant.ONE);
        formLabelEntity.setDel(DelEnum.NORMAL.getDel());
        formLabelEntity.setUpdateTime(DateTimeUtil.getInt());
        formLabelModel.update(formLabelEntity);

        //日志
        PaasFormEntityExt passForm = paasFormModel.getByKey(formLabelEntity.getFormId(), corpid);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_FORM_LABEL_RECOVER),loginUser.getName(),passForm.getName(),formLabelEntity.getName());
        mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.FORM_LABEL, OperateTypeEnum.RECOVER_LABEL,formLabelEntity.getId().toString(),formLabelEntity.getName(),memo,formLabelBaseDTO.getHttpHeader());


        FormLabelBaseVO formLabelBaseVO = new FormLabelBaseVO();
        formLabelBaseVO.setId(formLabelEntity.getId());
        return formLabelBaseVO;
    }


    @Override
    public FormLabelBaseVO completeDelete(FormLabelBaseDTO formLabelBaseDTO) throws XbbException {
        String corpid = formLabelBaseDTO.getCorpid();
        Long id = formLabelBaseDTO.getId();
        UserVO loginUser = formLabelBaseDTO.getLoginUser();
        FormLabelEntity formLabelEntity = formLabelModel.getByKey(id, corpid);
        if (Objects.isNull(formLabelEntity)) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120019);

        }

        Long formId = formLabelEntity.getFormId();
        Integer businessType = formLabelEntity.getBusinessType();

        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(BasicConstant.ID, id);
        jsonObject.put(BasicConstant.TYPE, LabelTypeEnum.FORM_LABEL.getType());
        param.put("formLabel", jsonObject.toJSONString());

        UserTeamEnum userTeamEnum = UserTeamEnum.getByCode(businessType);
        Integer entitysCount = 0;
        switch (userTeamEnum) {
            case CUSTOMER_TEAM:
                entitysCount = customerUserModel.getEntitysCount(param);
                break;
            case OPPORTUNITY_TEAM:
                entitysCount = opportunityUserModel.getEntitysCount(param);
                break;
            case CONTRACT_TEAM:
                entitysCount = contractUserModel.getEntitysCount(param);
                break;
            case CONTACT_TEAM:
                entitysCount = contactUserModel.getEntitysCount(param);
                break;
            case SUPPLIER_TEAM:
                entitysCount = supplierUserModel.getEntitysCount(param);
                break;
            case PURCHASE_TEAM:
                entitysCount = purchaseUserModel.getEntitysCount(param);
                break;
            case PRODUCTIONORDER_TEAM:
                entitysCount = productionOrderUserModel.getEntitysCount(param);
                break;
            case BOMBILL_TEAM:
                entitysCount = bomUserModel.getEntitysCount(param);
                break;
            case REFUND_TEAM:
                entitysCount = refundUserModel.getEntitysCount(param);
                break;
            case SUPPLIER_CONTACT_TEAM:
                entitysCount = supplierContactUserModel.getEntitysCount(param);
                break;
            case PAYMENT_TEAM:
                entitysCount = paymentUserModel.getEntitysCount(param);
                break;
            case PAY_PLAN_TEAM:
                entitysCount = payPlanUserModel.getEntitysCount(param);
                break;
            case QUOTATION_TEAM:
                entitysCount = quotationUserModel.getEntitysCount(param);
                break;
            case PAY_SHEET_TEAM:
                entitysCount = paymentSheetUserModel.getEntitysCount(param);
                break;
            case PAYMENT_SHEET_TEAM:
                entitysCount = paymentSheetUserModel.getEntitysCount(param);
                break;
            case CLUE_TEAM:
                entitysCount = clueUserModel.getEntitysCount(param);
                break;
            case MARKET_ACTIVITY_TEAM:
                entitysCount = marketActivityUserModel.getEntitysCount(param);
                break;
            case PAAS_TEAM:
                entitysCount = paasUserModel.getEntitysCount(param);
                break;
            default:
        }
        //查询该表单已启用的标签，启用列表里的也不允许删除
        param.clear();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.FORMID, formLabelBaseDTO.getFormId());
        param.put(ParameterConstant.BUSINESS_TYPE, businessType);
        param.put(StringConstant.SAAS_MARK, formLabelBaseDTO.getSaasMark());
        param.put(StringConstant.DISTRIBUTOR_MARK, formLabelBaseDTO.getDistributorMark());
        List<FormTeamSetEntity> formTeamSetEntities = formTeamSetModel.findEntities(param);

        List<Long> labelList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(formTeamSetEntities)) {
            labelList = formTeamSetEntities.get(Constant.ZERO).getLabelId().toJavaList(Long.class);
        }
        //在单据中有使用的或者表单设置页启用的，不允许彻底删除
        if (entitysCount > 0 || labelList.contains(id)) {
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120023);
        }

        formLabelEntity.setDel(DelEnum.APPROVE_STATUS.getDel());
        formLabelEntity.setUpdateTime(DateTimeUtil.getInt());
        formLabelModel.update(formLabelEntity);

        //日志
        PaasFormEntityExt passForm = paasFormModel.getByKey(formId, corpid);
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_FORM_LABEL_COMPLETE_DEL),loginUser.getName(),passForm.getName(),formLabelEntity.getName());
        mongoLogHelp.buildLog(corpid,loginUser.getUserId(),loginUser.getName(), OperateModuleTypeEnum.FORM_LABEL, OperateTypeEnum.DELETE,formLabelEntity.getId().toString(),formLabelEntity.getName(),memo,formLabelBaseDTO.getHttpHeader());


        FormLabelBaseVO formLabelBaseVO = new FormLabelBaseVO();
        formLabelBaseVO.setId(formLabelEntity.getId());
        return formLabelBaseVO;
    }

    @Override
    public LabelSortVO sort(LabelSortDTO labelSortDTO) throws XbbException {
        String corpid = labelSortDTO.getCorpid();
        List<LabelSortPojo> sortArray = labelSortDTO.getSortArray();
        List<Long> ids = new ArrayList<>();
        Map<Long, Integer> sortMap = new HashMap<>();
        sortArray.forEach(v -> {
            ids.add(v.getId());
            sortMap.put(v.getId(), v.getSort().intValue());
        });

        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put("idIn", ids);
        List<FormLabelEntity> formLabelEntities = formLabelModel.findEntities(param);

        long now = DateTimeUtil.getInt();
        formLabelEntities.forEach(v -> {
            v.setSort(sortMap.get(v.getId()));
            v.setUpdateTime(now);
        });

        formLabelModel.updateBatch(formLabelEntities, corpid);

        LabelSortVO labelSortVO = new LabelSortVO();
        labelSortVO.setIds(ids);
        return labelSortVO;
    }


    @Override
    public FormLabelListVO sampleList(FormLabelListDTO formLabelListDTO) throws XbbException {
        String corpid = formLabelListDTO.getCorpid();
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.FORMID, formLabelListDTO.getFormId());
        param.put(StringConstant.SAAS_MARK, formLabelListDTO.getSaasMark());
        param.put(ParameterConstant.BUSINESS_TYPE, formLabelListDTO.getBusinessType());
        param.put(StringConstant.DISTRIBUTOR_MARK, formLabelListDTO.getDistributorMark());

        List<FormLabelEntity> formLabelEntities = formLabelModel.findEntities(param);
        List<LabelPojo> labelListVO = new ArrayList<>();
        formLabelEntities.forEach(v -> labelListVO.add(new LabelPojo(v.getId(), v.getColor(), v.getName())));

        FormLabelListVO formLabelListVO = new FormLabelListVO();
        formLabelListVO.setLabelListVO(labelListVO);
        return formLabelListVO;
    }

    @Override
    public FormLabelListVO tabList(FormLabelListDTO formLabelListDTO) throws XbbException {
        String corpid = formLabelListDTO.getCorpid();
        Map<String, Object> param = new HashMap<>();
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.FORMID, formLabelListDTO.getFormId());
        param.put(StringConstant.SAAS_MARK, formLabelListDTO.getSaasMark());
        param.put(ParameterConstant.BUSINESS_TYPE, formLabelListDTO.getBusinessType());
        param.put(StringConstant.DISTRIBUTOR_MARK, formLabelListDTO.getDistributorMark());
        //先获取该表单启用的标签,在团队设置页会选择，所以若没有保存过设置，标签页一定是空的
        List<FormTeamSetEntity> formTeamSetEntityList = formTeamSetModel.findEntities(param);
        FormLabelListVO formLabelListVO = new FormLabelListVO();
        if(CollectionUtils.isNotEmpty(formTeamSetEntityList)){
            List<Object> labelList = new ArrayList<>(formTeamSetEntityList.get(Constant.ZERO).getLabelId());
            param.put(StringConstant.IDIN,labelList);
        }else{
            return formLabelListVO;
        }
        List<FormLabelEntity> formLabelEntities = formLabelModel.findEntities(param);
        List<LabelPojo> labelListVO = new ArrayList<>();
        formLabelEntities.forEach(v -> labelListVO.add(new LabelPojo(v.getId(), v.getColor(), v.getName())));
        formLabelListVO.setLabelListVO(labelListVO);
        return formLabelListVO;
    }


}
